{% extends "base.html" %}
{% load cctags %}
{% load ccfilters %}

{% block css %}
<link type="text/css" rel="stylesheet" href="/static/styles/routes.css"/>
<style type="text/css">
input[type="file"] {
    position: absolute;
    opacity: 0.0;
    filter :alpha(opacity=0.0);
    z-index: 99;
    cursor: pointer;
}
</style>
{% endblock %}

{% block scripts %}
{% if option.enable_gmap %}
    <script type="text/javascript" src="/static/js/highcharts.js"></script>
    <script type="text/javascript" src="/static/js/json2.js"></script>
    <script type="text/javascript" src="{% url views.localjavascript 'jquery.magicmap2.js' %}"></script>
    <script type="text/javascript" src="/static/js/jquery.blockUI.js"></script>
    <script type="text/javascript" src="/static/js/loadgpx.js"></script>
    <script type="text/javascript" src="/static/js/geoxml3.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var importfile = $("#importfile");

            var importdiv = $("#import");

            function relocation_fileinput(fileinput, button) {
                fileinput.width(button.width());
                fileinput.height(button.height());
                var button_position = button.offset();
                fileinput.css({
                    left: button_position.left + "px",
                    top: button_position.top +"px"
                });
            };
            $("#kml_button").mouseover(function(){
                relocation_fileinput(importfile, $("#kml_button"));
            });
            $("#gpx_button").mouseover(function(){
                relocation_fileinput(importfile, $("#gpx_button"));
            });

            importfile.change(function(){
                _reset_map();
                file_input_change(importfile);
            });

            var check_file_ext = function(filename) {
                var accepted_exts = "gpx,xml,kml";
                filename = filename.split('.');
                var ext = filename[filename.length-1].toLowerCase();
                return accepted_exts.indexOf(ext) >= 0;
            };
            var check_file_size= function(file_input) {
                if ($.browser.msie){ return true;}
                return (file_input[0].files[0].size  < {{ site_settings.upload_kml_limit }})
            };
            var file_input_change= function(fileinput){
                if(!fileinput.val()) {return false;}
                if (!check_file_ext(fileinput.val())) {
                    alert("{% _ 'unsupported file type' %}!");
                    return false;
                }
                if (!check_file_size(fileinput)) {
                    alert("{% _ 'file size exceed' %}! < {{ site_settings.upload_kml_limit|divide:"1048576"|floatformat:"1" }} M");
                    return false;
                }
                mmap.gmap().setMapTypeId(google.maps.MapTypeId.HYBRID);
                show_route(fileinput);
                /*upload_file(fileinput, function(url){
                    parser_file(url);
                });*/
            };
            var _reset_map = function(){
                mmap.reset();
                mmap.disable_directions();
            }
            var _get_addresses = function(parser){
                if( ! parser.hasRoute() ){
                    return false;
                }
                start_location = parser.getStartPos();
                end_location = parser.getEndPos();

                mmap.get_address(start_location, function(addr){
                    start_address = addr;
                    $("#start_address").val(start_address);
                });
                mmap.get_address(end_location, function(addr){
                    end_address = addr;
                    $("#end_address").val(end_address);
                });

                total_distance = parser.getDistance();  //m
                var distance = total_distance / 1000;  //m to km
                distance = mmap.get_localize_distance(distance);
                $("#distance").html(distance.toFixed(1)+" "+mmap.get_unit_str(0));

                preview_url =  parser.getPrevUrl(total_distance);
                $("#prev_img").attr("src", preview_url);
                $("#prev_img").show();

                $("#save_route").removeClass("disabled");
                $("#save_route").attr("disabled", false);

                $.unblockUI();

                var elevations = parser.getElevations();
                if (elevations.length>0){
                    mmap.show_elevations_chart(elevations, total_distance);
                } else {
                    $.growlUI('{% _ "No Valid Elevation" %}','{% _ "Get elevations from Google" %}', 4000);
                    var overview_path = parser.getOverviewPath(total_distance);
                    mmap.show_elevations_from_google(overview_path, total_distance);
                }
                return true;
            }
            var _show_kml = function(filename, str){
                route_type = "kml";
                kmlParser.parse(filename, null, str);
                return _get_addresses(kmlParser);
            }
            var _show_gpx = function(filename, str){
                route_type = "gpx";
                gpxParser.setxmlstr(str);
                gpxParser.centerAndZoom();
                gpxParser.addWaypointsToMap();
                gpxParser.addTrackpointsToMap();
                gpxParser.addRoutepointsToMap();

                return _get_addresses(gpxParser);
            }
            var show_route = function(fileinput){
                if ( typeof FileReader === 'undefined' ) {
                    alert( '{% _ "unsupported browser, recommend Chrome/Firefox"  %}' );
                    return;
                }

                $.blockUI({message: '<h1><img width="16" height="16" src="/static/images/loading.gif" /> {% _ "Importing" %}...</h1>'});
                
                var file = fileinput[0].files[0];
                var ext = file.name.split('.');
                ext = ext[ext.length-1].toLowerCase();

                var reader = new FileReader();
                reader.onload = function(evt){
                    var result = false;
                    if(ext == "kml"){
                        result = _show_kml(file.name, evt.target.result);
                    } else if (ext == "gpx"){
                        result = _show_gpx(file.name, evt.target.result);
                    } else if (ext == "xml"){
                        result = true;
                        if (!_show_gpx(file.name, evt.target.result)){
                            if(!_show_kml(file.name, evt.target.result)){
                                alert( '{% _ "unsupported file type" %}' );
                                result = false;
                            }
                        }
                    }
                    else {
                        alert( '{% _ "unsupported file type" %}' );
                    }
                    if (!result){
                        $.unblockUI();
                        alert('{% _ "There is no Route in this file." %}');
                    }
                }
                reader.readAsText(file);
            }
            var upload_file= function(fileinput, callback){
                $.blockUI({ message: '<h1><img src="/static/images/loading.gif" /> {% _ "Uploading" %}...</h1>' });

                $.getJSON("{{site_settings.host_site}}/apis/rest/?method=get_upload_signature&callback=?",
                    function(data){
                        if (data.status=="ok") {
                            var signature = data.signature;
                            _upload(signature, fileinput.val(), callback);
                        } else{
                            alert(data.message);
                            $.unblockUI();
                        }
                    }
                );

                var _upload = function(signature, filename, callback) {
                    $("#signature").val(signature);
                    $("#file_name").val(filename);

                    var getuploadurl = "{{site_settings.kml_site}}/getuploadurl/?signature=" + signature +
                            "&host="+ encodeURI("{{site_settings.host_site}}/apis/rest/");
                    jQuery.getScript(getuploadurl, function() {  //server response result,uploadurl,message
                        if (result=="ok"){
                            var upload_form = $("#upload_form");
                            upload_form.append(fileinput);
                            upload_form[0].action = uploadurl;
                            upload_form[0].submit();

                            var check_url = '{{site_settings.kml_site}}/getfileurl/'+signature;
                            //check result
                            var start_time = new Date();
                            var timeout = 4*60000;
                            var interval_control;
                            var running = false;
                            _check_result = function(){
                                if (running){ return; }
                                running = true;
                                $.getScript( check_url,
                                        function(){
                                            if (result=="ok") {
                                                //fileurl from server reponse
                                                clearInterval(interval_control);
                                                !!callback && callback(fileurl);
                                                return;
                                            } else {
                                                running = false;
                                            }
                                            var now = new Date();
                                            if((now - start_time) > timeout){
                                                clearInterval(interval_control);
                                                alert('{% _ "upload error" %}');
                                                $.unblockUI();
                                            }
                                            running = false;
                                        }
                                );
                            }
                            interval_control = setInterval("_check_result();", 3000);
                        } else {
                            alert(message);
                            $.unblockUI();
                        }
                    });
                };
            };

            
            var parser_file=function(url){
                $.unblockUI();
                $.blockUI({ message: '<h1><img src="/static/images/loading.gif" /> {% _ "Parsing" %}...</h1>' });
                $.getJSON(url+"?callback=?&encode=base64",
                    function(res){
                        $.unblockUI();
                        if (res.status=="ok") {
                            var ext = res.type;
                            var data = Utf8.decode(atob(res.base64));
                            if (ext == "kml"){
                                _show_kml(url, data);
                            } else if (ext == "gpx" || ext == "xml"){
                                _show_gpx(url, data);
                            } else {
                                alert( '{% _ "unsupported file type" %}' );
                            }
                        } else{
                            alert(res.message);
                        }
                    }
                );
            };


            var unit,
                direction_result,
                start_address,
                end_address,
                start_location,
                end_location,
                total_distance,
                route_type,
                preview_url;  //google static map url


            unit = google.maps.DirectionsUnitSystem.METRIC;
            {% ifeq unit.unit "imperial" %}
                unit = google.maps.DirectionsUnitSystem.IMPERIAL;
            {% endifeq %}

            //start init
            option = { mapTypeId: google.maps.MapTypeId.ROADMAP,
                       zoom: 4,
                       unit: unit
            }
            var mmap = new $.magicmap(option);

            $("#save_route").addClass("disabled");
            $("#save_route").attr("disabled", true);

            function directions_callback(directions){
                route_type = "gmap";

                direction_result = directions;

                var route = direction_result.routes[0];

                start_address = route.legs[0].start_address;
                end_address = route.legs[route.legs.length-1].end_address;

                start_location = route.legs[0].start_location;
                end_location = route.legs[route.legs.length-1].end_location;

                $("#start_address").val(start_address);
                $("#end_address").val(end_address);

                total_distance = mmap.calc_total_distance(route);  //m
                var distance = total_distance / 1000;  //m to km
                distance = mmap.get_localize_distance(distance);

                $("#distance").html(distance.toFixed(1)+" "+mmap.get_unit_str(0));

                preview_url = "http://maps.google.cn/maps/api/staticmap?size=640x480&sensor=false{% if user.language %}&language={{user.language}}{% endif %}"+
                        "&markers=color:green|label:S|"+
                        start_location.lat()+","+start_location.lng()+
                        "&markers=color:red|label:E|"+
                        end_location.lat()+","+end_location.lng() +
                        "&path=color:0xFF0000FF|enc:" +
                        route.overview_polyline.points;

                $("#save_route").removeClass("disabled");
                $("#save_route").attr("disabled", false);
            };

            function elevations_callback(elevationResult){
                $('html,body').animate({scrollTop: $("#route_info_table").offset().top}, 500);
            };

            $("#save_route").click(function(){
                if (! check_before_save()){
                    return;
                }
                if(route_type == "gmap"){
                    save_route();
                }else if(route_type == "kml" || route_type == "gpx"){
                    upload_file(importfile, function(url){
                        $("#file_url").val(url);
                        save_route();
                    });
                }else{
                    alert( "unsupported file type" );
                }
                return false;
            });

            function check_before_save(){
                $("#route_name").next("span").remove();
                name = $.trim($("#route_name").val());
                if (!name){
                    error = $('<span style="color:red;">{% _ "Pls input route name" %}</span>');
                    $("#route_name").after(error);
                    $("#route_name").focus(function(){
                        error.remove();
                    });
                    return false;
                }
                if (name.length>100){
                    error = $('<span style="color:red;">{% _ "Route Name" %} {% _ "too long" %}</span>');
                    $("#route_name").after(error);
                    $("#route_name").focus(function(){
                        error.remove();
                    });
                    return false;
                }

                if (/[<>;]+/.test(name)){
                    error = $('<span style="color:red;">[< > ;] {% _ "are not allowed" %}</span>');
                    $("#route_name").after(error);
                    $("#route_name").focus(function(){
                        error.remove();
                    });
                    return false;
                }
                if (!$.trim($("#start_address").val())) {
                    error = $('<span style="color:red;">*</span>');
                    $("#start_address").after(error);
                    $("#start_address").focus(function(){
                        error.remove();
                    });
                    return false;
                }
                if (!$.trim($("#end_address").val())) {
                    error = $('<span style="color:red;">*</span>');
                    $("#end_address").after(error);
                    $("#end_address").focus(function(){
                        error.remove();
                    });
                    return false;
                }
                if ((route_type != "gmap") && !importfile.val()){
                    alert('{% _ "no file to upload" %}');
                    return false;
                }
                return true;
            }

            function save_route(){
                $.blockUI({ message: '<h1><img src="/static/images/loading.gif" /> {% _ "Route Saving..." %}</h1>' });

                name = $.trim($("#route_name").val());
                $.post("{% url apis.apisviews.rest %}",
                      {method:"create_route",
                       name: name,
                       start_address: $("#start_address").val(),
                       end_address: $("#end_address").val(),
                       start_location: _S(start_location),
                       end_location: _S(end_location),
                       total_distance: total_distance,  //m
                       direction_result: _S(direction_result),
                       preview_url: preview_url,
                       route_type: route_type,
                       file_url: $("#file_url").val()
                      },
                      function(data){
                          data = _US(data);
                          if (data.status=="ok") {
                              alert("{% _ 'Route Saved' %}");
                              window.location.href="{% url routes.routesviews.showallroutes %}"+data.routeid;
                          }
                          else{
                              alert(data.message);
                          }
                          $.unblockUI();
                });
            }

            function reset_callback(){
                $("#save_route").addClass("disabled");
                $("#save_route").attr("disabled", true);
                $("#start_address").val("");
                $("#end_address").val("");
                $("#distance").html("");
                $("#route_name").val("");
                $("#file_url").val("");
                $("#prev_img").hide();

                direction_result = "";

                mmap.enable_directions({}, $("#route_directions"));
                gpxParser.reset();
                kmlParser.deleteAll();
                mmap.gmap().setMapTypeId(google.maps.MapTypeId.ROADMAP);
            }

            uicontrols = { map_container: $("#routes_map_container"),
                           searchbox: $("#routes_search_query"),
                           searchbtn: $("#routes_search_btn"),
                           waiting: $("#routes_search_waiting"),
                           searchresults: $("#routes_search_results"),
                           searchmsg: $("#routes_search_msg")
            };
            mmap.initmap({startcenter: $.magicmap.get_location_by_lang(),
                          controlsOption: {enable: true,
                                           reset_callback: reset_callback}
                          },
                          uicontrols);
            mmap.enable_directions({preserveViewport: false,
                                    draggable: true,
                                    callback: directions_callback},
                                   $("#route_directions"));
            mmap.enalbe_elevations({callback: elevations_callback},
                                   $("#routes_map_elevation_chart"));

            var kmlParser = new geoXML3.parser({map: mmap.gmap()});
            var gpxParser = new GPXParser(null, mmap.gmap());

        });
    </script>
{% endif %}
{% endblock %}

{% block menu %}
{% include '_menu_routes.html' %}
{% endblock %}

{% block main-page %}
<div id="create_route">
	{% if option.enable_gmap %}
	<div id="create_route_center">
        <h2 class="group_title">{% _ "Create Route" %}({% _ "Click to add point" %})</h2>
        <div class="tips">
            <div class="tips_content">
                <ul>
                    <li>{% _ "Left click to add a point(max 10 points)" %}</li>
                    <li>{% _ "You can drag marker or line to change directions" %}</li>
                </ul>
            </div>
            <a class="close" onclick="this.parentNode.style.display='none';return false;" href="javascript:void(0);">x</a>
        </div>
		{% include '_base_routes_map.html' %}
	</div>
    <div id="create_route_right">
        <h2 class="group_title">{% _ "Route Information" %}</h2>
        <table id="route_info_table">
            <tr><th colspan="2"></th></tr>
            <tr>
                <th scope="row">{% _ "Route Name" %}:</th>
                <td>
                <input id="route_name" name="route_name" class=":required" type="text" value=""/>
                </td>
            </tr>
            <tr>
                <th scope="row">{% _ "Start" %}:</th>
                <td>
                    <input id="start_address" name="start_address" class=":required" type="text" value=""/>
                </td>
            </tr>
            <tr>
                <th scope="row">{% _ "End" %}:</th>
                <td>
                    <input id="end_address" name="end_address" class=":required" type="text" value=""/>
                </td>
            </tr>
            <tr>
                <th scope="row">{% _ "Distance" %}:</th>
                <td id="distance"></td>
            </tr>
            <tr>
                <th scope="row"></th>
                <td><input type="submit" id="save_route" class="yellowbutton bigsize disabled" value="{% _ 'Save' %}"/></td>
            </tr>
        </table>
        <div id="import">
            <div class="tips">
                <div class="tips_content">
                    <ul>
                        <li>{% _ "Routes from GPS will be shown in Satellite Map because the Map in China was shifted by Martian!" %}</li>
                    </ul>
                </div>
                <a class="close" onclick="this.parentNode.style.display='none';return false;" href="javascript:void(0);">x</a>
            </div>
            <div id="import_kml" class="import_div">
                <img src="/static/images/kml.png">
                <input type="button" id="kml_button" class="greenbutton" value="{% _ 'Import' %} KML"/>
            </div>
            <div id="import_gpx" class="import_div">
                <img src="/static/images/gpx.png">
                <input type="button" id="gpx_button" class="greenbutton" value="{% _ 'Import' %} GPX"/>
            </div>
            <iframe name="frame_submit" id="frame_submit"  style="display:none" width="0" height="0"></iframe>
            <form id="upload_form" target="frame_submit" method="post" enctype="multipart/form-data">
                <input type="hidden" id="signature" name="signature" value=""/>
                <input type="hidden" id="file_name" name="file_name" value=""/>
                <input type="hidden" id="file_ext" name="file_ext" value=""/>
                <input type="file" id="importfile" name="file_binary"/>
            </form>
            <input type="hidden" id="file_url" name="file_url" class=":required" value=""/>
        </div>
        <div>
            <img id="prev_img" width="98%" style="display: none;"/>
        </div>
        <div id="route_directions"></div>
    </div>
	<div class="clear"></div>
	{% endif %}
</div>
{% endblock %}
